package com.edushare.common.mailer;

import java.text.SimpleDateFormat;

import com.edushare.common.util.URLUtils;
import com.edushare.common.vo.CourseInstances;
import com.edushare.common.vo.Departments;
import com.edushare.common.vo.OutgoingEmails;
import com.edushare.common.vo.Schedules;
import com.edushare.common.vo.Universities;
import com.edushare.common.vo.Users;

public class Schedule extends MailStringLoader {

	public Schedule(Users from, Users to, Schedules sch, Universities u){
		userTo = to;
		init(sch, from, u, u.getUniversityName());
	}
	
	public Schedule(Users from, Users to, Schedules sch, Departments dept){
		userTo = to;
		init(sch, from, dept, dept.getDeptName());
	}
	
	public Schedule(Users from, Users to, Schedules sch, CourseInstances course){
		userTo = to;
		init(sch, from, course.getCourse(),course.getCourse().getCourseName());
	}
	
	public Schedule(Users from, Users to, Schedules sch){
		userTo = to;
		init(sch, from, to, "you");
	}
	
	private Users userTo = null;
	private String mailString = MailBase.get().stringMap.get(MailBase.SCHEDULE_MAIL);
	
	private void init(Schedules sch, Users from, Object entity, String entityName){
		replaceMap.put("FROM_USER_URL", URLUtils.getHomePageURL(from));
		replaceMap.put("FROM_USER_NAME",from.getCompleteUserName());
		replaceMap.put("ENTITY_URL", URLUtils.getHomePageURL(entity));
		replaceMap.put("ENTITY_NAME",entityName);
		replaceMap.put("EVENT_TITLE", sch.getSchTitle());
		replaceMap.put("EVENT_START", new SimpleDateFormat("MMM d, yyyy hh:mm a").format(sch.getSchStart()));
		replaceMap.put("EVENT_END",new SimpleDateFormat("MMM d, yyyy hh:mm a").format(sch.getSchEnd()));
		replaceMap.put("EVENT_REPEAT",getRepeatRow(sch));
		replaceMap.put("EVENT_LOCATION",sch.getSchLocation());
		replaceMap.put("USER_URL", URLUtils.getHomePageURL(userTo));
		
		messageString = templateParser(mailString, replaceMap);
	}
	
	private String getRepeatRow(Schedules sch){
		if(sch.getFrequency() == Schedules.EVENT_ONCE_ONLY){
			return " ";
		}else{
			String repStr= "";
			switch(sch.getFrequency()){			
				case(Schedules.EVENT_DAILY):
					repStr = "Every day";
					break;
				case(Schedules.EVENT_MONTHLY):
					repStr = "Every month";
					break;
				case(Schedules.EVENT_WEEKLY):
					repStr = "Every week";
					break;
				default:
					repStr = " ";
			}
			
			return 		"<tr>"+
							"<td width='120px'>Repeats</td>" + 
							"<td width='230px'>" +
								"<span>" + repStr + "</span>" +
							"</td>" +
						"</tr>";
		}
	}
	
	@Override
	public OutgoingEmails send() {
		OutgoingEmails mail = new OutgoingEmails();
		mail.setContent(messageString);
		mail.setReceiverEmailId(userTo.getEmail());
		mail.setStatus(OutgoingEmails.EMAIL_TO_BE_SENT);
		mail.setCopyType(1);
		mail.setSubject("EduShare Event Notification");
		return mail;	
	}
}
